package com.backend.prototype.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.ZipUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipException;
import java.util.zip.ZipFile;

/**
 * 描述：
 *
 * @author xianggj
 * @Date 2021/11/22 10:51
 **/
@Controller
public class UploadController {

    @Value("${source.dir}")
    private String sourceDir;
    @Value("${zip.dir}")
    private String zipDir;
    @Value("${home.page}")
    private String home;

    @Autowired
    private HttpServletRequest request;
    /**
     *     跳转到上传文件的页面
     */
    @RequestMapping(value="/", method = RequestMethod.GET)
    public String goUploadImg() {
        //跳转到 templates 目录下的 uploadzip.html
        return "uploadzip";
    }

    /**
     *
     * @param file
     * @param request
     * @return
     */
    @RequestMapping(value="/upload", method = RequestMethod.POST)
    public String uploadImg(@RequestParam("file") MultipartFile file,
                            HttpServletRequest request, Model model) {
        model.addAttribute("url", getHeader());
        if (file.isEmpty()){
//            return "上传文件不能为空";
            model.addAttribute("msg", "上传文件不能为空");
            return "fail";
        }
        String originalFilename = file.getOriginalFilename();
        if (!StrUtil.endWith(originalFilename, ".zip")){
//            return "必须上传zip文件";
            model.addAttribute("msg", "必须上传zip文件");
            return "fail";
        }
        try {
            File zipFile = new File(zipDir);
            FileUtil.del(zipFile);
            FileUtil.mkdir(zipFile);
            File unzip = ZipUtil.unzip(file.getInputStream(), zipFile,
                    CharsetUtil.CHARSET_UTF_8);
            copy2Local(unzip);
        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute("msg", e.getMessage());
//            return e.getMessage();
            return "fail";
        }
        model.addAttribute("url", getHeader()+ "ui/index.html");
        return "success";
    }


    /**
     * 获取请求头
     *
     * @return
     */
    public String getHeader() {
        //获取当前请求地址 nginx代理后 这些地址发生改变
        String header = request.getScheme() + "://" +
                request.getServerName() + ":"+ request.getServerPort() +
                "/";
        return header;
    }
    /**
     * copy文件到本地
     * @param file
     */
    public  void copy2Local(File file) {
        File[] files = forSearchIndex(file);
        if (files == null){
            throw new RuntimeException("未发现index.html文件，上传文件格式错误");
        }
        File tarDir = new File(sourceDir);
        FileUtil.mkParentDirs(tarDir);
        FileUtil.del(tarDir);
        FileUtil.mkdir(tarDir);
        for (File f: files) {
            FileUtil.copy(f, tarDir, true);
        }
    }

    private File[] forSearchIndex(File unzip) {
        if (unzip.isDirectory()){
            File[] files = unzip.listFiles();
            for (File f : files) {
                if (home.equalsIgnoreCase(f.getName())){
                    return files;
                }
            }
            for (File f : files) {
                if (f.isDirectory()){
                    File[] files1 = forSearchIndex(f);
                    if (files1==null){
                        continue;
                    } else {
                        return files1;
                    }
                } else {
                    continue;
                }
            }

        }
        return null;
    }
}
